package com.pivotal.cloud.crypto.codec;

/**
 * @className: com.pivotal.cloud.security.crypto.codec.Base64
 * @projectName: PivotalCloud项目
 * @module: PivotalCloud项目-Base64类，主要位于Security安全模块-Base64模块
 * @content: Base64
 * @author: Powered by Marklin
 * @datetime: 2025-06-21 20:27
 * @version: 1.0.0
 * @copyright: Copyright © 2018-2025 PivotalCloud Systems Incorporated. All rights
 * reserved.
 */
public class Base64 {

	private static final byte EQUALS = 61;

	public Base64() {
	}

	static byte[] encode(byte[] bytes) {
		return Base64Codec.encode(bytes);
	}

	static byte[] decode(byte[] bytes) {
		return Base64Codec.decode(bytes);
	}

	static byte[] urlEncode(byte[] bytes) {
		byte[] b64Bytes = Base64Codec.encodeBytesToBytes(bytes, 0, bytes.length, 16);

		int length;
		for (length = b64Bytes.length; b64Bytes[length - 1] == EQUALS; --length) {
		}

		byte[] result = new byte[length];
		System.arraycopy(b64Bytes, 0, result, 0, length);
		return result;
	}

	static byte[] urlDecode(byte[] b64) {
		byte[] b64Bytes = null;
		int lMod4 = b64.length % 4;
		if (lMod4 == 0) {
			b64Bytes = b64;
		}
		else if (lMod4 == 2) {
			b64Bytes = pad(b64, 2);
		}
		else {
			if (lMod4 != 3) {
				throw new IllegalArgumentException("Invalid Base64 string");
			}

			b64Bytes = pad(b64, 1);
		}

		return Base64Codec.decode(b64Bytes, 0, b64Bytes.length, 16);
	}

	private static byte[] pad(byte[] bytes, int n) {
		int l = bytes.length;
		byte[] padded = new byte[l + n];
		System.arraycopy(bytes, 0, padded, 0, l);

		for (int i = l; i < l + n; ++i) {
			padded[i] = EQUALS;
		}

		return padded;
	}

}
